package cc.catface.api.filter;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.UUID;

/**过滤器-servlet|函数回*/
@Slf4j
//@Configuration//如有该注解(@Component)则urlPatterns不会生效(不会过滤)=>Application添加@ServletComponentScan
//@WebFilter(filterName = "CommonFilter", urlPatterns = {"/test/*"})
public class CommonFilter implements Filter {
    private static final String TAG = CommonFilter.class.getSimpleName();

    /*logback中的requestId*/
    private static final String REQUEST_ID_HEADER = "requestId";
    private static final String REQUEST_ID = "requestId";
    private static final String ProcessId_ID = "processId";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("init()");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestId = request.getHeader(REQUEST_ID_HEADER);
        if (requestId == null) {
            requestId = UUID.randomUUID().toString();
        }
        MDC.put(REQUEST_ID, requestId);
        response.setHeader(REQUEST_ID_HEADER, requestId);
        int processId = getProcessID();
        MDC.put(ProcessId_ID, String.valueOf(processId));
        try {
            chain.doFilter(request, response);
        } finally {
            MDC.clear();
        }

        /*日志&响应头*/
        StringBuffer url = request.getRequestURL();
        String uri = request.getRequestURI();
        //设置响应头
        response.setHeader("HA", "VA");

        //打印日志
        log.info("\n{}\n┃请求url=>{}\n┃请求uri=>{}\n{}",
                "┌-------------------------------------" + TAG,
                url, uri,
                "└-------------------------------------");
        chain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        log.info("destroy()");
    }


    private static int getProcessID() {
        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        return Integer.parseInt(runtimeMXBean.getName().split("@")[0]);
    }
}
